//
//  MapViewController.m
//  家校互通
//
//  Created by 姬鑫宇 on 15/4/29.
//  Copyright (c) 2015年 姬鑫宇. All rights reserved.
//

//地图ViewController

#define MYBUNDLE_NAME @ "mapapi.bundle"
#define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
#define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]

#import "MapViewController.h"
#import "Extra.h"
#import "UserLocationManager.h"

#import "PaoPaoView.h"

@interface MapViewController (){
    BMKPointAnnotation* pointAnnotation;
}

@property (nonatomic, assign) BOOL isSetPosition;

@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isSetPosition                       = YES;
    [_mapView setZoomLevel:18];
    _locService                          = [[BMKLocationService alloc]init];
    _mapView.delegate                    = self;
    _locService.delegate                 = self;
    [self addPointAnnotationWithlng:_lng andLat:_lat];
    //    lat 40.060747,long 116.309079
    [self addPointAnnotationWithlng:116.30941 andLat:40.06582];
    [self addPointAnnotationWithlng:116.309923 andLat:40.06125];
    [self addPointAnnotationWithlng:116.326000 andLat:40.039827];
    [self addPointAnnotationWithlng:116.386000 andLat:40.104827];
    [self addPointAnnotationWithlng:116.356000 andLat:40.024827];
    
    [_locService startUserLocationService];
    _mapView.showsUserLocation           = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode            = BMKUserTrackingModeNone;//设置定位的状态
    _mapView.showsUserLocation           = YES;//显示定位图层
    //    [Extra globalTimelinePostsWithBlock:^(NSArray *posts, NSError *error) {
    //        NSLog(@"fdadfkjak::::::%@",posts);
    //        Extra *extraModel = [posts objectAtIndex:0];
    //        [self addPointAnnotationWithlng:extraModel.lng andLat:extraModel.lat];
    //    }];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)passLocationValue
{
    BMKCoordinateRegion viewRegion       = BMKCoordinateRegionMake([UserLocationManager sharedInstance].clloction.coordinate, BMKCoordinateSpanMake(0.02f,0.02f));
    BMKCoordinateRegion adjustedRegion   = [_mapView regionThatFits:viewRegion];
    [_mapView setRegion:adjustedRegion animated:YES];
    
}
#pragma mark -设置定位圆点属性
-(void)setUserImage
{
    //用户位置类
    BMKLocationViewDisplayParam* param   = [[BMKLocationViewDisplayParam alloc] init];
    param.locationViewOffsetY            = 0;//偏移量
    param.locationViewOffsetX            = 0;
    param.isAccuracyCircleShow           = YES;//设置是否显示定位的那个精度圈
    param.isRotateAngleValid             = NO;
    [_mapView updateLocationViewWithParam:param];
}

-(IBAction)startLocation:(id)sender
{
    //    NSLog(@"进入普通定位态");
    //    [_locService startUserLocationService];
    //    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    //    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    //    _mapView.showsUserLocation = YES;//显示定位图层
    _isSetPosition                       = YES;
}

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    //    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    //    _locService.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    //    _mapView.delegate = nil; // 不用时，置nil
    //    _locService.delegate = nil;
}

- (void)dealloc {
    if (_mapView) {
        _mapView                             = nil;
    }
}

- (void)addPointAnnotationWithlng:(double)lng andLat:(double)lat
{
    if (pointAnnotation == nil) {
        pointAnnotation                      = [[BMKPointAnnotation alloc]init];
    }
    BMKPointAnnotation *pointAnnotation1 = [[BMKPointAnnotation alloc]init];
    CLLocationCoordinate2D coor;
    coor.latitude                        = lat;
    coor.longitude                       = lng;
    pointAnnotation1.coordinate          = coor;
    [_mapView setCenterCoordinate:coor animated:YES];
    pointAnnotation1.title               = @"test";
    //    pointAnnotation1.subtitle = @"此Annotation可拖拽!";
    if (lng<_lng)
        _lng                                 = lng;
    if (lat<_lat) {
        _lat                                 = lat;
    }
    
    [_mapView addAnnotation:pointAnnotation1];
}

#pragma mark -
#pragma mark implement BMKMapViewDelegate


// 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    NSString *AnnotationViewID           = @"renameMark";
    //普通annotation
    //    if (annotation == pointAnnotation) {
    //        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    //        if (annotationView == nil) {
    //            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
    //            UIView *viewForImage=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 126, 65)];
    //            UIImageView *backGround = [[UIImageView alloc]initWithFrame:viewForImage.frame];
    //            backGround.image = [UIImage imageNamed:@"单个背景"];
    //            [viewForImage addSubview:backGround];
    //
    //            UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(9, 9, 40, 40)];
    //            imageview.layer.cornerRadius = 20;
    //            imageview.layer.masksToBounds = YES;
    //            [imageview setImage:[UIImage imageNamed:@"icon01.jpg"]];
    //            [viewForImage addSubview:imageview];
    //
    //            UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(55, 9, 62, 40)];
    //            label.font = [UIFont systemFontOfSize:15];
    //            label.text=@"尼格买提";
    //            label.backgroundColor=[UIColor clearColor];
    //            [viewForImage addSubview:label];
    //
    //            annotationView.image = [UIImage imageNamed:@"地图定位"];
    ////            annotationView.image=[self getImageFromView:viewForImage];
    ////            annotationView.centerOffset = CGPointMake(-50, -(annotationView.frame.size.height * 0.5));
    ////            annotationView.annotation = annotation;
    ////            annotationView.canShowCallout = NO;
    //
    //            BMKActionPaopaoView *paopao = [[BMKActionPaopaoView alloc]initWithCustomView:viewForImage];
    //            annotationView.paopaoView = paopao;
    //
    //        }
    //        return annotationView;
    //    }else
    //        return [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
    //    ;
    BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    if (annotationView == nil) {
        annotationView                       = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        UIView *viewForImage=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 126, 65)];
        UIImageView *backGround              = [[UIImageView alloc]initWithFrame:viewForImage.frame];
        backGround.image                     = [UIImage imageNamed:@"单个背景"];
        [viewForImage addSubview:backGround];
        
        UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(9, 9, 40, 40)];
        imageview.layer.cornerRadius         = 20;
        imageview.layer.masksToBounds        = YES;
        [imageview setImage:[UIImage imageNamed:@"icon01.jpg"]];
        [viewForImage addSubview:imageview];
        
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(55, 9, 62, 40)];
        label.font                           = [UIFont systemFontOfSize:15];
        label.text=@"尼格买提";
        label.backgroundColor=[UIColor clearColor];
        [viewForImage addSubview:label];
        
        annotationView.image                 = [UIImage imageNamed:@"地图定位"];
        //            annotationView.image=[self getImageFromView:viewForImage];
        //            annotationView.centerOffset = CGPointMake(-50, -(annotationView.frame.size.height * 0.5));
        //            annotationView.annotation = annotation;
        //            annotationView.canShowCallout = NO;
        
        BMKActionPaopaoView *paopao          = [[BMKActionPaopaoView alloc]initWithCustomView:viewForImage];
        annotationView.paopaoView            = paopao;
        
    }
    return annotationView;
}

-(UIImage *)getImageFromView:(UIView *)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image                       = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

// 当点击annotation view弹出的泡泡时，调用此接口
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view;
{
    NSLog(@"paopaoclick");
}

#pragma mark -
#pragma mark implement BMKLocationServiceDelegate
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    _mapView.showsUserLocation           = YES;//显示定位图层
    [_mapView updateLocationData:userLocation];
    
    if (_isSetPosition) {
        BMKCoordinateRegion region;
        region.center.longitude              = userLocation.location.coordinate.longitude;
        region.center.latitude               = userLocation.location.coordinate.latitude;
        
        double latitude                      = _lat - userLocation.location.coordinate.latitude;
        double longitude                     = _lng - userLocation.location.coordinate.longitude;
        double spanDelta                     = sqrt(longitude * longitude + latitude * latitude);
        
        spanDelta                            = spanDelta * 1.5;
        
        region.span.latitudeDelta            = spanDelta;
        region.span.longitudeDelta           = spanDelta;
        if (_mapView) {
            _mapView.region                      = region;
        }
        _isSetPosition                       = NO;
    }
    
    //    [_locService stopUserLocationService];
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"stop locate");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"location error");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

